package com.rchat.pocmini.db;

import android.content.Context;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by ljd on 2017/3/16.
 */

public final class BeanManager {

    private static final String TAG = "BeanManager";

    private static BeanManager instance = new BeanManager();

    public static BeanManager get() {
        return instance;
    }

    private Map<Class<?>, Creator<?>> creatorMap = new HashMap<Class<?>, Creator<?>>();

    private ConcurrentMap<Class<?>, Object> beanMap = new ConcurrentHashMap();

    private BeanManager() {
        init();
    }

    private void init() {
        registerCreator(PocDbHelper.class, (Creator<PocDbHelper>) new PocDbHelper.Creator());
//        registerCreator(ChannelDaoImpl.class,new ChannelDaoImpl.Creator());
        registerCreator(MemoryDataStoreModel.class, new MemoryDataStoreModel.Creator());
        registerCreator(MessageDaoImpl.class, (Creator<MessageDaoImpl>) new MessageDaoImpl.Creator());
//        registerCreator(SessionDaoImpl.class, new SessionDaoImpl.Creator());
//        registerCreator(SessionMemberDaoImpl.class, new SessionMemberDaoImpl.Creator());
//        registerCreator(BroadcastDaoImpl.class, new BroadcastDaoImpl.Creator());
    }

    private <T> void registerCreator(Class<T> clazz, Creator<T> creator) {
        creatorMap.put(clazz, creator);
    }

    public <T> T getBean(Class<T> clazz, Context context) {

        Creator<T> creator = (Creator<T>) creatorMap.get(clazz);
        if (creator == null) {
            return null;
        }
        if (!creator.isSingleton()) {
            return creator.create(context);
        }

        if (!beanMap.containsKey(clazz)) {
            T o = creator.create(context);
            beanMap.putIfAbsent(clazz, o);
        }

        return (T) beanMap.get(clazz);
    }

    public void clearBeans() {
        beanMap.clear();
    }

    public interface Creator<T> {
        T create(Context context);

        boolean isSingleton();
    }
}

